#!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>

from __future__ import (unicode_literals, division, absolute_import,
                        print_function)
import sys
import os
import tempfile
import shutil
import subprocess
import re

base = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(base, 'scripts'))

from pkgs.constants import pkg_ext
from pkgs.utils import install_package


def create_bundle(osname, bitness=''):
    pkg_dir = os.path.join(base, 'build', osname)
    if bitness:
        pkg_dir = os.path.join(pkg_dir, bitness)
    if osname == 'linux':
        pkg_dir = os.path.join(pkg_dir, 'sw')
    tdir = tempfile.mkdtemp(dir=pkg_dir)
    name = osname
    if bitness:
        name += '-' + bitness
    name += '.tar.xz'
    print('Installing packages for', osname, bitness, 'from', pkg_dir, '...')
    try:
        for x in os.listdir(pkg_dir):
            if x.endswith('.' + pkg_ext):
                install_package(os.path.join(pkg_dir, x), tdir)
        with tempfile.NamedTemporaryFile(suffix='.tar.xz') as tf:
            print('\tCreating bundle...')
            os.fchmod(tf.fileno(), 0o644)
            subprocess.check_call(['tar', '-caf', tf.name] + os.listdir(tdir), cwd=tdir)
            subprocess.check_call(['scp', tf.name, 'download.calibre-ebook.com:/srv/download/travis/' + name])
    finally:
        shutil.rmtree(tdir)


if len(sys.argv) > 1:
    which = sys.argv[-1]
    m = re.match(r'(osx|win|linux)(32|64)?', sys.argv[-1])
    if m is None:
        raise SystemExit('Usage: export [linux32|linux64|win32|win64|osx]')
    osname = m.group(1)
    bitness = m.group(2) if osname != 'osx' else ''
    create_bundle(osname, bitness)
else:
    for osname in 'linux win'.split():
        for bitness in '64 32'.split():
            create_bundle(osname, bitness)
    create_bundle('osx')
